{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# 4. 条件与循环"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.1  条件语句"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "9"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "x = -9\n",
    "if x < 0 :\n",
    "    y = -x\n",
    "else:\n",
    "    y = x\n",
    "\n",
    "y\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "green\n"
     ]
    }
   ],
   "source": [
    "if id == 0:\n",
    "    print('red')\n",
    "elif id == 1:\n",
    "    print('yellow')\n",
    "else:\n",
    "    print('green')  "
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.2 省略判断条件用法\n",
    "\n",
    "- String : 空字符串解析为False,其余为True\n",
    "- Int : 0解析为Flase,其余为True\n",
    "- Bool: True 为 True,Flase 为Falase\n",
    "- list/tuple/dict/set ： iterable为空解析为Flase,其余为True\n",
    "- Object : None解析为False,其余为True"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.3 循环语句\n",
    "\n",
    "- for\n",
    "- while\n",
    "\n",
    "Python 中的数据结构只要是可迭代的（iterable），比如列表、集合等等，那么都可以通过下面这种方式遍历：\n",
    "\n",
    "// for item in iterable:\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "l = [1, 2, 3, 4]\n",
    "for item in l:\n",
    "    print(item)\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4.3.1 字典遍历\n",
    "字典本身只有键是可迭代的，如果我们要遍历它的值或者是键值对，就需要通过其内置的函数 values() 或者 items() 实现。其中，values() 返回字典的值的集合，items() 返回键值对的集合。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "name\n",
      "dob\n",
      "gender\n",
      "jason\n",
      "2000-01-01\n",
      "male\n",
      "key: name, value: jason\n",
      "key: dob, value: 2000-01-01\n",
      "key: gender, value: male\n"
     ]
    }
   ],
   "source": [
    "d = {'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'}\n",
    "for k in d: # 遍历字典的键\n",
    "    print(k)\n",
    "\n",
    "\n",
    "for v in d.values(): # 遍历字典的值\n",
    "    print(v)\n",
    "\n",
    "for k, v in d.items(): # 遍历字典的键值对\n",
    "    print('key: {}, value: {}'.format(k, v))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4.3.2 通过索引遍历\n",
    "\n",
    "- range\n",
    "- enumerate"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n",
      "1\n",
      "2\n",
      "3\n",
      "4\n"
     ]
    }
   ],
   "source": [
    "l = [1, 2, 3, 4, 5, 6, 7]\n",
    "for index in range(0, len(l)):\n",
    "    if index < 5:\n",
    "        print(l[index])        \n",
    "\n",
    "l = [1, 2, 3, 4]\n",
    "index = 0\n",
    "while index < len(l):\n",
    "    print(l[index])\n",
    "    index += 1"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1\n",
      "2\n",
      "3\n",
      "4\n",
      "5\n"
     ]
    }
   ],
   "source": [
    "l = [1, 2, 3, 4, 5, 6, 7]\n",
    "for index, value in enumerate(l):\n",
    "    if index < 5:\n",
    "        print(value)\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "##### 4.3.3 for & while 循环效率\n",
    "\n",
    "range() 函数是直接由 C 语言写的，调用它速度非常快。而 while 循环中的“i += 1”这个操作，得通过 Python 的解释器间接调用底层的 C 语言；并且这个简单的操作，又涉及到了对象的创建和删除（因为 i 是整型，是 immutable，i += 1 相当于 i = new int(i + 1)）。所以，显然，for 循环的效率更胜一筹。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [],
   "source": [
    "i = 0\n",
    "while i < 1000000:\n",
    "    i += 1\n",
    "\n",
    "for i in range(0, 1000000):\n",
    "    pass"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 4.4 条件与循环的复用\n",
    "\n",
    "```python\n",
    "expression1 if condition else expression2 for item in iterable\n",
    "# 等同于如下表达式\n",
    "for item in iterable:\n",
    "    if condition:\n",
    "        expression1\n",
    "    else:\n",
    "        expression2\n",
    "\n",
    "# 没有else\n",
    "expression for item in iterable if condition\n",
    "\n",
    "\n",
    "[(xx, yy) for xx in x for yy in y if xx != yy]\n",
    "# 等同于如下表达式\n",
    "l = []\n",
    "for xx in x:\n",
    "    for yy in y:\n",
    "        if xx != yy:\n",
    "            l.append((xx, yy))\n",
    "\n",
    "```"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "['Today', 'Sunday']\n"
     ]
    }
   ],
   "source": [
    "text = ' Today,  is, Sunday'\n",
    "text_list = [s.strip() for s in text.split(',') if len(s.strip()) > 3]\n",
    "print(text_list)\n",
    "\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 概要\n",
    "- 在条件语句中，if 可以单独使用，但是 elif 和 else 必须和 if 同时搭配使用；\n",
    "- 而 If 条件语句的判断，除了 boolean 类型外，其他的最好显示出来。\n",
    "- 在 for 循环中，如果需要同时访问索引和元素，你可以使用 enumerate() 函数来简化代码。\n",
    "- 写条件与循环时，合理利用 continue 或者 break 来避免复杂的嵌套，是十分重要的。\n",
    "- 要注意条件与循环的复用，简单功能往往可以用一行直接完成，极大地提高代码质量与效率。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[{'name': 'jason', 'dob': '2000-01-01', 'gender': 'male'},\n",
       " {'name': 'mike', 'dob': '1999-01-01', 'gender': 'male'},\n",
       " {'name': 'nancy', 'dob': '2001-02-01', 'gender': 'female'}]"
      ]
     },
     "execution_count": 22,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "attributes = ['name', 'dob', 'gender']\n",
    "values = [['jason', '2000-01-01', 'male'], ['mike', '1999-01-01', 'male'],['nancy', '2001-02-01', 'female']]\n",
    "\n",
    "l = [dict(zip(attributes, value)) for value in values]\n",
    "l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### zip 用法"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[('张三', 20), ('李四', 25), ('王五', 30)]\n",
      "{'张三': 20, '李四': 25, '王五': 30}\n",
      "[('张三', 20), ('李四', 25), ('王五', 30)]\n",
      "['张三', '李四', '王五']\n",
      "[20, 25, 30]\n"
     ]
    }
   ],
   "source": [
    "# 最简单的例子\n",
    "names = ['张三', '李四', '王五']\n",
    "ages = [20, 25, 30]\n",
    "scores = [85, 92, 88]\n",
    "\n",
    "# 转换为列表\n",
    "pairs = list(zip(names, ages))\n",
    "print(pairs)  # [('张三', 20), ('李四', 25), ('王五', 30)]\n",
    "\n",
    "# 转换为字典\n",
    "person_dict = dict(zip(names, ages))\n",
    "print(person_dict)  #\n",
    "\n",
    "# 解压缩\n",
    "# 将zip对象解压缩回原始序列\n",
    "zipped = list(zip(names, ages))\n",
    "print(zipped)\n",
    "names2, ages2 = zip(*zipped)\n",
    "print(list(names2))  # ['张三', '李四', '王五']\n",
    "print(list(ages2))   \n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.12.10"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
